package com.appbee.gdata.youtube.client.ui;

import javax.inject.Inject;

import com.appbee.core.client.listener.ISearchListener;
import com.appbee.core.client.ui.ISimpleFilterView;
import com.appbee.gdata.youtube.client.presenter.EntrySuggestOracle;
import com.appbee.gdata.youtube.client.presenter.SearchPresenter;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.client.ui.Widget;

public class SearchView extends Composite implements SearchPresenter.FilterView,ISimpleFilterView
{

	private static SearchViewUiBinder uiBinder = GWT
			.create(SearchViewUiBinder.class);

	interface SearchViewUiBinder extends UiBinder<Widget, SearchView>
	{
	}
	@UiField(provided=true)
	SuggestBox searchBox;
	
	private ISearchListener listener;

	@Inject
	public SearchView(EntrySuggestOracle oracle)
	{
		searchBox = new SuggestBox(oracle);
		initWidget(uiBinder.createAndBindUi(this));
		
		searchBox.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>()
		{
			
			@Override
			public void onSelection(SelectionEvent<Suggestion> event)
			{
				listener.onSearch();
			}
		});
		
		searchBox.addKeyDownHandler(new KeyDownHandler()
		{
			
			@Override
			public void onKeyDown(KeyDownEvent event)
			{
				if(event.getNativeKeyCode()==KeyCodes.KEY_ENTER)
					listener.onSearch();
			}
		});
	}
	
	public void setListener(ISearchListener listener)
	{
		this.listener = listener;
	}



	@Override
	public String getValue()
	{
		return searchBox.getValue();
	}

	@Override
	public void setValue(String value)
	{
		searchBox.setValue(value);
	}

	@Override
	public String getSearchValue()
	{
		return searchBox.getValue();
	}

	public void focus()
	{
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand()
		{
			
			@Override
			public void execute()
			{
				searchBox.setFocus(true);
			}
		});
	}


}
